package com.android.manghe.common.webview

import android.Manifest
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.app.ActivityCompat
import com.android.base.frame.presenter.IView
import com.android.base.frame.presenter.XPresenter
import com.android.base.frame.view.MVPActivity
import com.android.manghe.R
import com.android.manghe.cache.StatusHolder
import com.android.manghe.cache.UserHolder
import com.android.manghe.common.activity.PaySuccessActivity
import com.android.manghe.common.model.WebViewUserInfo
import com.android.manghe.config.Config
import com.android.manghe.user.activity.LoginActivity
import com.android.manghe.utils.MoneyUtil
import com.fm.openinstall.OpenInstall
import com.google.gson.Gson
import com.umeng.analytics.MobclickAgent
import kotlinx.android.synthetic.main.activity_simple_web_view.*
import java.util.*

class SimpleWebViewActivity : MVPActivity<XPresenter<IView>>() {

    companion object {
        fun showActivity(context: Context, url: String, title: String) {
            val intent = Intent(context, SimpleWebViewActivity::class.java)
            intent.putExtra("url", url)
            intent.putExtra("title", title)
            context.startActivity(intent)
        }

        fun showActivity(
            context: Context,
            url: String,
            title: String,
            isCheckUserInfo: Boolean = true
        ) {
            val intent = Intent(context, SimpleWebViewActivity::class.java)
            intent.putExtra("url", url)
            intent.putExtra("title", title)
            intent.putExtra("isCheckUserInfo", isCheckUserInfo)
            context.startActivity(intent)
        }
    }

    private var isCheckUserInfo = true

    override fun initData(savedInstanceState: Bundle?) {
        titleBar.setToolbar(intent.getStringExtra("title")).setTitleAndStatusBgColor(R.color.white)
            .setLeftIcon(R.mipmap.icon_back_black)
        isCheckUserInfo = intent.getBooleanExtra("isCheckUserInfo", true)
        val settings = webView.settings
        settings.javaScriptEnabled = true //允许运行JS脚本
        settings.domStorageEnabled = true
        initListener()
        val url = intent.getStringExtra("url")
        webView.loadUrl(url)
    }

    private fun initListener() {
        webView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                if (!isCheckUserInfo) {
                    return
                }
                try {
                    val userInfo = UserHolder.getUserInfo(this@SimpleWebViewActivity)
                    if (userInfo == null) {
                        finish()
                        open(LoginActivity::class.java)
                    } else {
                        val jsonUser = Gson().toJson(
                            WebViewUserInfo(
                                userInfo.TOKEN,
                                userInfo.UID,
                                userInfo.UNAME,
                                userInfo.avatar
                            )
                        )
                        val js = "window.localStorage.setItem('user','$jsonUser');"
                        val jsUrl = "javascript:localStorage.setItem('user','$jsonUser');"
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            view?.evaluateJavascript(js, null)
                        } else {
                            view?.loadUrl(jsUrl)
                        }
                    }
                    if (!TextUtils.isEmpty(url) && url!!.contains("/home/shengfupay_success")) {
                        OpenInstall.reportEffectPoint(
                            Config.OpenInstall_Voucher,
                            MoneyUtil.changeY2F(StatusHolder.mCurrentVoucherPrice).toLong()
                        )
                        val mapValue: MutableMap<String, String> =
                            HashMap()
                        mapValue["charge"] = "1"
                        MobclickAgent.onEventValue(
                            this@SimpleWebViewActivity,
                            "charge",
                            mapValue,
                            MoneyUtil.changeY2F(StatusHolder.mCurrentVoucherPrice)
                        )
                        //PayTrack
                        try {
                            val successPayMap =
                                HashMap<String, String>()
                            successPayMap["userid"] = UserHolder.getUID(this@SimpleWebViewActivity)
                            successPayMap["orderid"] = System.currentTimeMillis().toString()
                            successPayMap["item"] = "购券"
                            successPayMap["amount"] =
                                MoneyUtil.changeY2F(StatusHolder.mCurrentVoucherPrice).toString()
                            MobclickAgent.onEvent(
                                this@SimpleWebViewActivity,
                                "__finish_payment",
                                successPayMap
                            )
                        } catch (e: Exception) {
                        }
                        finish()
                        open(PaySuccessActivity::class.java)
                    }
                } catch (e: Exception) {
                    print(e)
                }
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_simple_web_view
    }
}